import { ref } from 'vue'
import store from '@/store'
import { defineStore } from 'pinia'
import { constantRoutes, dynamicRoutes } from '@/router'
import { flatMultiLevelRoutes } from '@/router/helper'
import routeSettings from '@/config/route'
import { $t } from '@/languages/index'

const hasPermission = (roles, route) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some(role => routeRoles.includes(role)) : true
}

const filterDynamicRoutes = (routes, roles) => {
  const res = []
  routes.forEach(route => {
    const tempRoute = { ...route }
    if (hasPermission(roles, tempRoute)) {
      if (tempRoute.children) {
        tempRoute.children = filterDynamicRoutes(tempRoute.children, roles)
      }
      res.push(tempRoute)
    }
  })
  return res
}

export const usePermissionStore = defineStore('permission', () => {
  /** 可访问的路由 */
  const routes = ref([])
  /** 有访问权限的动态路由 */
  const addRoutes = ref([])

  /** 根据角色生成可访问的 Routes（可访问的路由 = 常驻路由 + 有访问权限的动态路由） */
  const setRoutes = roles => {
    const accessedRoutes = filterDynamicRoutes(dynamicRoutes, roles)
    console.log(accessedRoutes, 'accessedRoutes')
    _set(accessedRoutes)
  }

  /**（没有根据角色过滤掉的） 所有路由 = 所有常驻路由 + 所有动态路由 */
  const setAllRoutes = () => {
    _set(dynamicRoutes)
  }

  const _set = accessedRoutes => {
    // 动态静态合并
    const allRoutes = constantRoutes.concat(accessedRoutes)
    const allNewRoutes = setRouterTitle(allRoutes, $t)
    routes.value = allNewRoutes
    addRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes
  }

  /**设置路由title */
  const setRouterTitle = (newRoute, t) => {
    return newRoute.map(route => {
      const tmp = { ...route }
      // 翻译路由标题
      if (tmp.meta?.title && tmp.meta?.i18nKey) {
        tmp.meta.title = t(tmp.meta?.i18nKey)
      }
      if (tmp.children && tmp.children.length > 0) {
        tmp.children = setRouterTitle(tmp.children, t)
      }
      return tmp
    })
  }

  return { routes, addRoutes, setRoutes, setAllRoutes, setRouterTitle }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
